﻿using MailBox.App_Code;
using MailBox.App_Code.dto;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MailBox
{
    public partial class _Default : Page
    {
        UserLoginDTO user = null;
        DataUtils utils = new DataUtils();
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                user = GetUserLogin();
                if (!IsPostBack)
                {
                    if (!user.isClient)
                    {
                        hdfCurrentPage.Value = "0";
                        refresh("next");

                    }
                }
            }
            catch (Exception ex)
            { Common.logs(user, "PageLoad", ex, Common.logType.error); }
        }
        const string HTML_TAG_PATTERN = "<.*?>";
        string StripHTML(string inputString)
        {
            return Regex.Replace
              (inputString, HTML_TAG_PATTERN, string.Empty);
        }
        public string Left(string s, int len)
        {
            s = StripHTML(s);
            if (len == 0 || s.Length == 0)
                return "";
            else if (s.Length <= len)
                return s;
            else
                return s.Substring(0, len)+"...";
        }
        int count = 20;
        decimal currentid;
        public void refresh(string mode)
        {
            try
            {
                mode = mode == "" ? "next" : mode;
                decimal.TryParse(hdfCurrentID.Value, out currentid);
                if (currentid == 0)
                {
                    currentid = 1000000000;
                    btnPre.Disabled = true;
                }
                else
                    btnPre.Disabled = false;
                string type = Request.QueryString["mode"];
                type = type + "" == "" ? "Inbox" : type;
                DataTable source = null;
                string email = Session["EmailLogin"] + "";
                string keyword = Server.HtmlDecode(Request.QueryString["kw"] + "") + "";
                if (type == "Inbox" || type + "" == "")
                {
                    this.Title = "Hộp thư";
                }
                else if (type == "Sent" || type + "" == "")
                {
                    this.Title = "Thư đã gửi";
                }
                else if (type == "Draft" || type + "" == "")
                {
                    this.Title = "Thư nháp";
                }
                else if (type == "Spam" || type + "" == "")
                {
                    this.Title = "Hộp thư rác";
                }
                else //if (type == "Inbox" || type + "" == "")
                    this.Title = "Thùng rác";
                source = utils.GetInbox(type, email, currentid, mode, count, keyword);
                //}
                rptMail.DataSource = source;
                rptMail.DataBind();
                hdfMaxID.Value = source.Compute("max(id)", "") + "";
                hdfMinID.Value = source.Compute("min(id)", "") + "";
                Common.logs(null, string.Format("currentpage:{0}, currentid: {1}, max:{2}, min:{3}", hdfCurrentPage.Value, currentid, hdfMaxID.Value, hdfMinID.Value), null, Common.logType.info);
                decimal total = 0;
                if (source.Rows.Count > 0)
                    decimal.TryParse(source.Rows[0]["total"] + "", out total);
                lblPaging.Text = string.Format("{0} - {1} trên tổng {2}", Convert.ToInt32(hdfCurrentPage.Value) * count + 1, Convert.ToInt32(hdfCurrentPage.Value) * count + source.Rows.Count, total);
                if (source.Rows.Count == 20) btnNext.Disabled = false;
                else btnNext.Disabled = true;
            }
            catch (Exception ex)
            {
                Common.logs(null, HttpContext.Current.Request.RawUrl + "- refresh", ex, Common.logType.error);
            }
        }

        private UserLoginDTO GetUserLogin()
        {
            UserLoginDTO userLogin = (UserLoginDTO)Session["UserLogin"];
            if (userLogin == null)
                Response.Redirect("login.aspx");
            else return userLogin;
            return null;
        }
        static FAMailUtils.MailGun.SendMail send = new FAMailUtils.MailGun.SendMail(System.Configuration.ConfigurationManager.AppSettings["api-key"]);

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static void sendmail(string from, string to, string cc, string bcc, string subject, string content, bool isSent)
        {
            try
            {
                content = content.Replace("/daunhay/","'");
                to = to.Replace("/", "");
                cc = cc.Replace("/", "");
                bcc = bcc.Replace("/", "");
                string attachFiles = "AttachFiles/" + from + "/temps";
                if (!Directory.Exists(HttpContext.Current.Server.MapPath(attachFiles)))
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(attachFiles));
                string[] files = Directory.GetFiles(HttpContext.Current.Server.MapPath(attachFiles));
                string FileAttached = Guid.NewGuid().ToString();
                List<string> fileAttches = new List<string>();
                if (isSent)
                    foreach (string file in files)
                    {
                        if (!Directory.Exists(HttpContext.Current.Server.MapPath("AttachFiles/" + from)))
                            Directory.CreateDirectory(HttpContext.Current.Server.MapPath("AttachFiles/" + from));
                        if (!Directory.Exists(HttpContext.Current.Server.MapPath(attachFiles).Replace("temps", FileAttached)))
                            Directory.CreateDirectory(HttpContext.Current.Server.MapPath(attachFiles).Replace("temps", FileAttached));
                        string newfile = file.Replace("temps", FileAttached);
                        fileAttches.Add(newfile);
                        File.Move(file, newfile);
                    }
                string domain = from.Split('@')[1];
                DataUtils utils = new DataUtils();
                string senderName = utils.GetNameByEmail(from);
                string recieverName = utils.GetNameByEmail(to);
                if (isSent)
                    send.SendHtmlMessage(domain, senderName, from, to, cc, bcc, subject, content, false, fileAttches);
                OutboxDTO dto = new OutboxDTO();
                dto.body = content;
                dto.reciever = to;
                dto.cc = cc;
                dto.bcc = bcc;
                dto.isSent = isSent;
                dto.recievername = recieverName == "" ? to : recieverName;
                dto.sender = from;
                dto.subject = subject.Split(',')[0];
                if (files.Length > 0)
                    dto.FileAttached = FileAttached;
                else dto.FileAttached = "";
                utils.AddOutBox(dto);
                HttpContext.Current.Session["CurrentEmail"] = dto;
            }
            catch (Exception ex)
            {
                Common.logs(null, "sendmail", ex, Common.logType.error);
            }
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static void deletefile(string file)
        {
            string attachFiles = "AttachFiles/" + HttpContext.Current.Session["EmailLogin"] + "/temps";
            File.Delete(HttpContext.Current.Server.MapPath(attachFiles + "/" + file));
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static void deletealltempfiles()
        {
            string attachFiles = "AttachFiles/" + HttpContext.Current.Session["EmailLogin"] + "/temps";
            if (Directory.Exists(HttpContext.Current.Server.MapPath(attachFiles)))
            {
                string[] files = Directory.GetFiles(HttpContext.Current.Server.MapPath(attachFiles));
                foreach (string file in files)
                    File.Delete(file);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static Dictionary<string, string> getautocompletedata()
        {
            DataUtils utils = new DataUtils();
            DataTable source = utils.GetAutocompleteByEmail(HttpContext.Current.Session["EmailLogin"] + "");

            var keyValues = new Dictionary<string, string>();
            foreach (DataRow row in source.Rows)
            {
                bool result = false;
                foreach(var item in keyValues)
                {
                     result = !FAMailUtils.EmailTools.IsEmail(row[0] + "") || item.Key == row[0] + "";
                    if (result)
                        break;
                }
                if (!result)
                    keyValues.Add(row[0] + "", row[1] + "");
            }
            source.Dispose();
            return keyValues;
        }
        

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string getsignature()
        {
            string email = HttpContext.Current.Session["EmailLogin"] + "";
            DataUtils utils = new DataUtils();
            string signature = utils.GetSignatureByEmail(email);
            return signature;
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static OutboxDTO CreateOrLoadCurrent()
        {
            OutboxDTO outbox = new OutboxDTO();
            return outbox;
        }
        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            refresh("");
        }

        protected void btnDelete_ServerClick(object sender, EventArgs e)
        {

            string type = Request.QueryString["mode"];
            foreach (RepeaterItem item in rptMail.Items)
            {
                foreach (Control control in item.Controls)
                    if (control is CheckBox)
                        if (((CheckBox)control).Checked)
                        {
                            foreach (Control cont in item.Controls)
                                if (cont is HiddenField)
                                {
                                    utils.DeleteEmail(((HiddenField)cont).Value, type);
                                }
                        }
            }

            refresh("");
        }

        protected void btnSeleteAll_ServerClick(object sender, EventArgs e)
        {
            foreach (RepeaterItem item in rptMail.Items)
            {
                foreach (Control control in item.Controls)
                    if (control is CheckBox)
                        ((CheckBox)control).Checked = ((CheckBox)control).Checked ? false : true;
            }
        }

        protected void btnPre_ServerClick(object sender, EventArgs e)
        {
            hdfCurrentID.Value = hdfMaxID.Value;
            hdfCurrentPage.Value = (hdfCurrentPage.Value == "" ? 0 : Convert.ToInt32(hdfCurrentPage.Value) - 1) + "";
            refresh("pre");
        }

        protected void btnNext_ServerClick(object sender, EventArgs e)
        {
            hdfCurrentID.Value = hdfMinID.Value;
            hdfCurrentPage.Value = (hdfCurrentPage.Value == "" ? 0 : Convert.ToInt32(hdfCurrentPage.Value) + 1) + "";
            refresh("next");
        }
    }
}